import java.util.Arrays;
import java.util.HashMap;

public class FourSumCount {

    public int fourSumCount1(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        Arrays.sort(nums4);
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums4.length; i++) {
            map.put(nums4[i], map.getOrDefault(nums4[i], 0) + 1);
        }
        int ans = 0;
        for (int i = 0; i < nums1.length; i++) {
            for (int j = 0; j < nums2.length; j++) {
                for (int k = 0; k < nums3.length; k++) {
                    int l = 0;
                    int r = nums4.length - 1;
                    int sum = nums1[i] + nums2[j] + nums3[k];
                    while (l < r) {
                        int mid = l + (r - l) / 2;
                        if (nums4[mid] + sum < 0) {
                            l = mid + 1;
                        } else {
                            r = mid;
                        }
                    }
                    if (nums4[l] + sum == 0) ans += map.get(nums4[l]);
                }
            }
        }
        return ans;
    }

    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        HashMap<Integer, Integer> map1 = new HashMap<>();
        int ans = 0;
        for (int i = 0; i < nums1.length; i++) {
            for (int j = 0; j < nums2.length; j++) {
                int sum = nums1[i] + nums2[j];
                map1.put(sum, map1.getOrDefault(sum, 0) + 1);
            }
        }
        for (int i = 0; i < nums3.length; i++) {
            for (int j = 0; j < nums4.length; j++) {
                int sum = nums1[i] + nums2[j];
                ans += map1.getOrDefault(-sum, 0);
            }
        }
        return ans;
    }
}
